var mSession = require('../model/SessionEntity');

var uuid = require('node-uuid');

var ccSession = function(sessions) {
	var mw = function(req, res, next) {
		debug.log("	Resolving Session");

		var request = req.body || {};
		var cookie = req.cookies || {};

		var session = {};

		// Is there a sesion field in the request?
		if ((typeof (request.session) != 'undefined')
		// Is the session field blank
		&& (request.session != '')
		// Is the session ID valid?
		&& (typeof (sessions[request.session]) != 'undefined')) {
			session = sessions[request.session];
			debug.log("	Request - Found Session: " + session.id);
			
			req.session = session;
			session.bindClient(req, res, next);

			// Is there a sesion field in the cookie?
		} else if ((typeof (cookie.session) != 'undefined')
		// Is the session field blank
		&& (cookie.session != '')
		// Is the session ID valid?
		&& (typeof (sessions[cookie.session]) != 'undefined')) {
			session = sessions[cookie.session];
			debug.log("	Cookie - Found Session: " + session.id);
			
			req.session = session;
			session.bindClient(req, res, next);
		} else {
			session = new mSession(uuid.v4());
			debug.log("	Creating Session: " + session.id);
			
			res.cookie("session", session.id);
			req.session = session;

			session.bindClient(req, res, next);

			sessions[session.id] = session;
		}
	};

	return mw;
};

module.exports = ccSession;
